from flask import Flask
from flask import request, abort

from center.database.dbmodel import DomainDBModel

app = Flask(__name__)


@app.route("/domains", methods=['GET'])
def list_domains():
    domaindb = DomainDBModel()
    return domaindb.list()


@app.route("/domains/<string:domain_name>", methods=['GET'])
def get_domain(domain_name):
    domaindb = DomainDBModel()
    query = {"name": domain_name}
    return domaindb.find(query)


@app.route('/domains', methods=['POST'])
def add_domain():
    if not request.json or not 'name' in request.form:
        abort(400)
    domain = {
        'name': request.form['domain_name'],
        'description': request.form.get('description', "")
    }
    domaindb = DomainDBModel()
    domaindb.insert(domain)
    return domain, 201
